package com.kzm.configuration;

import com.google.common.collect.Maps;
import com.kzm.common.exception.ConflictException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.Map;

@ControllerAdvice
public class CustomExceptionHandler {

    /**
     * 使用自定义异常拦截来处理Controller的异常，这边是可以拦截Interceptor的异常，但是不能拦截shiro filter的异常的异常
     * 异常优先顺序：@ControllerAdvice -> ErrorPageRegistrar -> ErrorController
     *
     */


    /**
     * 处理ForbiddenException
     */
    @ExceptionHandler({ConflictException.class})
    public ModelAndView forbiddenException(HttpServletRequest request, HttpServletResponse response, ConflictException exception) {
        if (request.getHeader("X-Requested-With") == null) {
            ModelAndView mav = new ModelAndView();
            mav.addObject("url", request.getRequestURL());
            mav.addObject("message", exception.getMessage());
            mav.setViewName("error/409");
            return mav;
        } else {
            Map<String, Object> json = getResponseMap(HttpStatus.FORBIDDEN.value(), exception.getMessage());
            return new ModelAndView(new MappingJackson2JsonView(), json);
        }
    }


    //返回不可更改的HashMap
    private Map<String, Object> getResponseMap(Integer httpStatus, String message) {
        Map<String, Object> result = Maps.newHashMap();
        result.put("httpStatus", httpStatus);
        result.put("message", message);

        return Collections.unmodifiableMap(result);
    }


}
